package com.distributed.netty.encode;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import io.netty.buffer.ByteBuf;

/**
 * @desc	解序列化工具类	
 * @author	高增源
 * @time	2021年11月18日
 */
public class ByteUtils {

	/**
	 * @desc  1.将字节数组转变为对象
	 * @param bytes
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Object byteToObject(byte[] bytes) throws IOException, ClassNotFoundException {
		ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
		ObjectInputStream oi  = new ObjectInputStream(bi);
		Object obj = oi.readObject();
		bi.close();
		oi.close();
		return obj;
	}
	public static byte[] objectToByty(Object object) throws IOException{
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		ObjectOutputStream oos=new  ObjectOutputStream(baos);
		oos.writeObject(object);
		byte[] bs=baos.toByteArray();
		oos.close();
		baos.close();
		return bs;
	}
	/**
	 * @desc 将缓冲区对象转为字节数组
	 * @param in
	 * @return 
	 */
	public static byte[] byteBufToBytes(ByteBuf in) {
		byte[] bytes = new byte[in.readableBytes()];
		in.readBytes(bytes);
		return bytes;
	}
}	
